/**
 * Created by LiH on 2018/7/10.
 */
import takeDefaultOptions from '../lib/takeDefaultOptions'
import loadingAnimation from '../components/ZuicoolLoading'

let $vm;

export default {
  install(Vue){
    const Loading = Vue.extend(loadingAnimation);

    if(!$vm){
      $vm = new Loading({
        el: document.createElement('div')
      });
      document.body.appendChild($vm.$el)
    }

    const defaults = takeDefaultOptions($vm);

    // fade out animation setTimeout
    let fadeOut = null;

    Vue.$ZCLoading = {
      show(options = {}){
        options = Object.assign({}, defaults, options, {show: true});
        for(let i in options){
          if(options.hasOwnProperty(i)){
            $vm[i] = options[i]
          }
        }

        if(fadeOut){
          clearTimeout(fadeOut);
          fadeOut = null;
          $vm.$el.style.transition = '';
          $vm.$el.style.opacity = 1;
        }
        $vm.visible = true;
      },

      hide(options = {}){
        if(options.fadeOut){
          const _elm = $vm.$el;

          _elm.style.transition = 'opacity .5s';
          _elm.style.opacity = 0;
          fadeOut = setTimeout(function () {
            _elm.style.transition = '';
            _elm.style.opacity = 1;
            $vm.visible = false;
          }, 500)
        } else {
          $vm.visible = false;
        }
      }
    };

    Vue.mixin({
      created(){
        this.$ZCLoading = Vue.$ZCLoading
      }
    })
  }
}
